let main;
let filter;
let receiver;
let tag = false;

// let urovoPlatformModule = uni.requireNativePlugin("TH-PlatformSDK");

//定义广播
const init = (onReceive) => {
  // 第一个参数 0:手动模式 1:连续模式
  // 第二个参数 0:广播输出模式 1:键盘输出模式
  // urovoPlatformModule.setScanMode(0, 0);

  main = plus.android.runtimeMainActivity(); //获取activity
  // 扫描设置的广播名称
  const IntentFilter = plus.android.importClass("android.content.IntentFilter");
  filter = new IntentFilter();
  filter.addAction("android.intent.ACTION_DECODE_DATA"); //监听扫描广播

  receiver = plus.android.implements(
    "io.dcloud.feature.internal.reflect.BroadcastReceiver",
    {
      onReceive: function (context, intent) {
        plus.android.importClass(intent);
        // 扫描设置的开发者选项--键值名称
        var code = intent.getStringExtra("barcode_string"); // 监听对应PDA广播标签
        // 业务
        //防重复
        if (tag) return;
        tag = true;
        setTimeout(function () {
          tag = false;
        }, 150);
        // 扫描成功，调用自己的业务逻辑
        onReceive && onReceive(code);
      },
    }
  );
};

//注册监听
const registerReceiver = () => {
  /* #ifdef APP-PLUS */
  main.registerReceiver(receiver, filter);
  /* #endif */
};
//停止广播监听扫码
const unregisterReceiver = () => {
  /* #ifdef APP-PLUS */
  main.unregisterReceiver(receiver);
  /* #endif */
};

export const scan = {
  init,
  registerReceiver,
  unregisterReceiver,
};
